package com.designpatterns.proxy.myproxy;

import java.lang.reflect.Method;

public class MyMedium implements MyInvocationHandler {

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Class cl = target.getClass();
        System.out.println("被代理对象："+target.getClass());
        Class<?>[] interfaces=cl.getInterfaces();
        System.out.print("被代理对象实现的接口是：");
        for(Class<?> i:interfaces){
            System.out.print(i.getName()+", ");
        }
        System.out.println("");
        return MyProxy.newProxyInstance(new MyClassLoader(),interfaces,this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object obj = method.invoke(target,args);
        after();
        return obj;
    }

    private void before(){
        System.out.println("我是中介，开始帮"+target.getClass().getName());
        System.out.println("----------------------");
    }

    private void after(){
        System.out.println("OK");
        System.out.println("----------------------");
    }
}
